package com.huitongmaoyi.ai.dao;

import com.huitongmaoyi.ai.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {

    /**
     * 根据用户名查询用户ID
     * @param username 用户名
     * @return 用户ID，若用户不存在则返回null
     */
    public Long getUserIdByUsername(String username) {
        String sql = "SELECT id FROM users WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getLong("id");
            }
        } catch (SQLException e) {
            System.err.println("查询用户ID失败: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据用户ID查询用户名
     * @param userId 用户ID
     * @return 用户名，若用户不存在则返回null
     */
    public String getUsernameByUserId(Long userId) {
        if (userId == null) {
            return null;
        }

        String sql = "SELECT username FROM users WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setLong(1, userId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getString("username");
            }
        } catch (SQLException e) {
            System.err.println("查询用户名失败: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查用户是否存在
     * @param username 用户名
     * @return 存在返回true，否则返回false
     */
    public boolean exists(String username) {
        return getUserIdByUsername(username) != null;
    }
}